<?php
if (!(defined('IN_IA'))) 
{
	exit('Access Denied');
}
require_once('Dir.php');
require_once('PclZip.php');
class DiygwcomAction extends WeModuleSite
{

    public function __construct()
    {
        $this->modulename=MODULE_NAME;
    }

	public function template($filename = '', $type = TEMPLATE_INCLUDEPATH, $account = false) 
	{

		global $_W;
		global $_GPC;
		if (empty($filename)) 
		{
			$filename = str_replace('_', '/', $_W['routes']);
		}
        $do=$_GPC['do'].'/';
        $name =MODULE_NAME;
        $moduleroot = IA_ROOT . '/addons/'.$name;

        if(defined('IN_SYS')) {
            $source = IA_ROOT . "/web/themes/{$_W['template']}/{$name}/{$filename}.html";
            $compile = IA_ROOT . "/data/tpl/web/{$_W['template']}/{$name}/{$filename}.tpl.php";
            if(!is_file($source)) {
                $source = IA_ROOT . "/web/themes/default/{$name}/{$filename}.html";
            }
            if(!is_file($source)) {
                $source = $moduleroot . "/template/web/{$filename}.html";
            }
            if(!is_file($source)) {
                $source = IA_ROOT . "/template/web/{$filename}.html";
            }
            if(!is_file($source)) {
                $source = IA_ROOT . "/web/themes/{$_W['template']}/{$filename}.html";
            }
            if(!is_file($source)) {
                $source = IA_ROOT . "/web/themes/default/{$filename}.html";
            }
        } else {
            $source = IA_ROOT . "/app/themes/{$_W['template']}/{$name}/{$filename}.html";
            $compile = IA_ROOT . "/data/tpl/app/{$_W['template']}/{$name}/{$filename}.tpl.php";
            if(!is_file($source)) {
                $source = $moduleroot . "/template/mobile/{$filename}.html";
            }
            if(!is_file($source)) {
                $source = IA_ROOT . "/app/themes/default/{$name}/{$filename}.html";
            }

            if(!is_file($source)) {
                $source = IA_ROOT . "/template/mobile/{$filename}.html";
            }
            if(!is_file($source)) {
                $source = IA_ROOT . "/template/webapp/{$filename}.html";
            }
            if(!is_file($source)) {
                $source = IA_ROOT . "/app/themes/{$_W['template']}/{$filename}.html";
            }
            if(!is_file($source)) {
                if (in_array($filename, array('header', 'footer', 'slide', 'toolbar', 'message'))) {
                    $source = IA_ROOT . "/app/themes/default/common/{$filename}.html";
                } else {
                    $source = IA_ROOT . "/app/themes/default/{$filename}.html";
                }
            }
        }

        if(!is_file($source)) {
            exit("Error: template source '{$do}{$filename}' is not exist!");
        }
        $paths = pathinfo($compile);
        $compile = str_replace($paths['filename'], $_W['uniacid'] . '_' . $paths['filename'], $compile);
        if (DEVELOPMENT || !is_file($compile) || filemtime($source) > filemtime($compile)) {
            template_compile($source, $compile, true);
        }
        return $compile;
	}

	public function checkSubmit($key, $time = 2, $message = '操作频繁，请稍后再试!') 
	{
		global $_W;
		$open_redis = function_exists('redis') && !(is_error(redis()));
		if ($open_redis) 
		{
			$redis_key = $_W['setting']['site']['key'] . '_' . $_W['account']['key'] . '_' . $_W['uniacid'] . '_' . $_W['openid'] . '_mobilesubmit_' . $key;
			$redis = redis();
			if ($redis->setnx($redis_key, time())) 
			{
				$redis->expireAt($redis_key, time() + $time);
			}
			else 
			{
				return error(-1, $message);
			}
		}
		return true;
	}

	public function getUserInfo(){
        // 获取用户信息
        if (empty($_W['fans']['nickname'])) {
            load()->model('mc');
            mc_oauth_userinfo();
        }
        $user_info = mc_fetch($_W['openid']);
        return $user_info;
    }
	public function checkSubmitGlobal($key, $time = 2, $message = '操作频繁，请稍后再试!') 
	{
		global $_W;
		$open_redis = function_exists('redis') && !(is_error(redis()));
		if ($open_redis) 
		{
			$redis_key = $_W['setting']['site']['key'] . '_' . $_W['account']['key'] . '_' . $_W['uniacid'] . '_mobilesubmit_' . $key;
			$redis = redis();
			if ($redis->setnx($redis_key, time())) 
			{
				$redis->expireAt($redis_key, time() + $time);
			}
			else 
			{
				return error(-1, $message);
			}
		}
		return true;
	}


	public function getDashboardExtends($dashboardid){
        $result = pdo_getall(getTableName('DASHBOARD_EXTEND'),array("dashboard_id"=>$dashboardid));
        //去掉不必要的属性值，否则查询数据库会出错
        $data=[];
        foreach ($result as $key => $value) {
            $data[$value['name']]=$value['value'];
        }
        $homepageid= pdo_get(getTableName('PAGE'), array('dashboard_id'=>$dashboardid,'template'=>'mobile','is_home'=>'1'), array('id'));
        if($homepageid){
            $data["homePage"]=DiygwcomUtil::to_mobile_url($this->createMobileUrl('page_index', array('m'=>'diygwcom_app','pid'=>$homepageid['id'])));
        }
        return $data;
    }
    /**
     * 删除表格非自己的属性
     * @param $table
     * @param $map
     */
    public function removeMap($tableFullName, $map)
    {
        global $_GPC;

        $result = pdo_fetchall("SHOW FULL COLUMNS FROM  ims_".$tableFullName);

        $fields = array();
        foreach($result as $value) {
            $fields[] = $value["Field"];
        }

        //去掉不必要的属性值，否则查询数据库会出错
        foreach ($map as $key => $value) {
            if (!in_array($key, $fields)) {
                unset($map[$key]);
            }
        }
        return $map;
    }

    protected  function lists ($tablename,$where=array(),$order='',$field=true){
        global $_GPC;

        $result =pdo_fetchall("SHOW INDEX FROM ims_" . $tablename);
        $pk="id";
        foreach($result as $value) {
            if($value['Key_name'] == 'PRIMARY'){
                $pk=$value['Column_name'];
            }
        }

        $orderArray=[];
        if($order===null||($order==='' && !empty($pk))){
            $orderArray[]= $pk.' desc';
        }elseif($order){
            $orderArray[]=$order;
        }

        $psize 	= 10;
        if( isset($_GPC['r'])){
            $psize = safe_gpc_int($_GPC['r']);
        }else if( isset($_GPC['row'])){
            $psize = safe_gpc_int($_GPC['row']);
        }

        $index 	= max(1, intval($_GPC['page']));


        $plist 	= pdo_getslice($tablename, $where , array($index, $psize), $total, array(), '',$orderArray);
        $rows=[];
        foreach ($plist as $item){
            foreach($item as $key => $value){
                $item[$key]=htmlspecialchars_decode($value);
            }
            $rows[]=$item;
        }
        $list['rows']=$rows;
        $list['total']=$total;
        $list['totalPage']=ceil($total / $psize);
        return $list;
    }

    public function  getErrorPage($message){
        $message=$message;
        global $_GPC, $_W;
        $dashboardid = safe_gpc_int($_GPC["dashboardid"]);
        include $this->template("login/perror");
    }

    public function  getErrorMessage($message){
        echo json_encode(['status'=>'error','message'=>$message]);
    }

    public function  getPageMessage($message,$rows=[],$total=1,$totalPage=1){
        echo json_encode(['status'=>'success','message'=>$message,'rows'=>$rows,'total'=>$total,'totalPage'=>$totalPage]);
    }

    public function  getSuccessMessage($message){
        echo json_encode(['status'=>'success','message'=>$message]);
    }

    public function data()
    {
        global $_GPC;
        try {
            /*$Authorization = $_SERVER['HTTP_AUTHORIZATION'];

            if(cache($Authorization)==null){
                $list['Authorization']=$Authorization;
                $list['code']='-1';
                $list['message']='请求鉴权 API 失败，网络异常或鉴权服务器错误';
                return json_encode($list);
            }*/
            $type = safe_gpc_string($_GPC["type"]);
            $columns =$_GPC["columns"];
            if(empty($columns)){
                //去掉不必要的属性值，否则查询数据库会出错
                $table = $this->getTable();//获取不带前缀的表名
                $map = $this->removeMap($table, $_GPC);
                $order = safe_gpc_string($_GPC["order"]);

                $list = $this->lists ($table,$map,$order);

                $link_table = safe_gpc_string($_GPC["link_table"]);
                if($list['total'] >0 && !empty($link_table)){

                    $datas = $list['rows'];
                    $attr = array();
                    foreach ($datas as $item) {
                        $attr[]=$item['link_id'];
                    }
                    $link_table= $this->getTbName($link_table);
                    if($link_table){
                        $linkDatas = pdo_getall($link_table,["id"=>$attr]);
                        $gdata = array();
                        foreach ($linkDatas as $ritem) {//遍历实际表数据
                            foreach ($datas as $item) {
                                if($ritem['id']==$item['link_id']){//遍历主表数据
                                    $tmp=array_merge($ritem,$item);
                                    $gdata[]=$tmp;
                                }
                            }
                        }
                        $list['rows']=$gdata;
                    }
                }
                $list['status']='success';
                echo json_encode($list);
            }else{
                $columns = json_decode(htmlspecialchars_decode($columns),true);
                $count_json = count($columns);
                $tables = array();
                $dashboardid = safe_gpc_string($_GPC["dashboardid"]);
                for ($i = 0; $i < $count_json; $i++){
                    $column = $columns[$i];
                    $dashboardid = $column['dashboard_id'];
                    $columnList = null;
                    if(!empty($tables[$column['form_id']])){
                        $columnList =$tables[$column['form_id']];
                        $columnList[] = $column;
                        $tables[$column['form_id']] = $columnList;
                    }else{
                        $columnList = array();
                        $columnList[] = $column;
                        $tables[$column['form_id']] = $columnList;
                    }
                }

                $sql = "select ";
                $selectTables = array();
                $wheres = array();
                foreach ($tables as $formid => $columns) {

                    $map=[];
                    $map["name"]=$dashboardid."_".$formid;
                    $tableName = $this->getTbName($map["name"]);
                    if(!$tableName){
                        $message=[
                            'status'       => "success",
                            'message'       => "获取数据成功",
                            'total'        =>0,
                            'rows'         =>[]
                        ];
                        echo json_encode($message);
                        return;
                    }

                    $tableAlias["name"]=$tableName;
                    $alias = "t".$formid;
                    $tableAlias["alias"]=$alias;
                    $selectTables[] = $tableAlias;

                    $idExist=false;//判断ID值是否存在，如果存在则不加ID值
                    $fields = array();
                    foreach ($columns as $column) {//遍历配置字段拼接SQL
                        $field = $column['field'];
                        if(in_array($field, $fields)){//判断查询字段是否已经存在，如果存在，跳过
                            continue;
                        }
                        $fields[]=$field;
                        if($field=="id"){
                            $sql=$sql." ".$alias.".id"." id_".$formid."_1 , ";
                            $idExist= true;
                        }else if($field=="user_id"){
                            $sql=$sql." ".$alias.".create_time"." id_".$formid."_2 , ";
                            $idExist= true;
                        }else if($field=="create_time"){
                            $sql=$sql." ".$alias.".create_time"." id_".$formid."_3 , ";
                            $idExist= true;
                        }else{
                            $sql=$sql." ".$alias.".".$field.", ";
                        }
                    }
                    if(!$idExist){
                        $sql=$sql." ".$alias.".id"." id_".$formid."_1 , ";
                    }
                }
                $sql=substr($sql,0,strripos($sql,","));
                $sql.=" from ";
                foreach ($selectTables as $i=>$alias) {
                    $sql=$sql." ims_".$alias["name"]." as ".$alias["alias"].", ";
                }
                $sql=substr($sql,0,strripos($sql,","));

                $links = safe_gpc_string($_GPC["links"]);
                $links = json_decode($links);

                foreach ($links as $i=>$link) {
                    $fromOperator = $link->fromOperator;
                    $fromOperator =substr($fromOperator,4);
                    $fromConnector = $link->fromConnector;
                    $fromConnector =substr($fromConnector,7);
                    $toOperator = $link->toOperator;
                    $toOperator =substr($toOperator,4);
                    $toConnector = $link->toConnector;
                    $toConnector =substr($toConnector,6);
                    $sql.=" where t$fromOperator.$fromConnector=t$toOperator.$toConnector";
                }

                $sql .=" order by ";
                foreach ($selectTables as $i=>$alias) {
                    $sql=$sql." ".$alias["alias"].".create_time, ";
                }
                $sql=substr($sql,0,strripos($sql,","));
                $sql .=" desc ";

                $psize 	= 10;
                if( isset($_GPC['r'])){
                    $psize = safe_gpc_int($_GPC['r']);
                }else if( isset($_GPC['row'])){
                    $psize = safe_gpc_int($_GPC['row']);
                }

                $offset = safe_gpc_int($_GPC['offset']);

                $countSql = " select count(1) total from ($sql) t";

                $total = pdo_fetchcolumn($countSql);
                $sql.=" limit $offset , $psize ";
                $plist = pdo_fetchall($sql);

                echo json_encode( [
                    'status'       => "success",
                    'message'       => "获取数据成功",
                    'total'        => $total,
                    'rows'         =>$plist
                ]);
                return;
            }
        } catch (\Exception $e) {
            $info = ['status'=>'error', 'message'=>'获取数据失败'.$e];
            echo json_encode($info);
        }
    }

    /**
     * 创建UUID
     * @return string
     */
    function create_guid(){
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $uuid = substr($charid, 0, 8).substr($charid, 8, 4).substr($charid,12, 4).substr($charid,16, 4).substr($charid,20,12);
        return $uuid;
    }

    public function save()
    {
        global $_GPC;global $_W;
        try {
            $table = $this->getTable();
            if(!$table){
                echo json_encode(['status'=>'error', 'message'=>'表不存在']);
                return;
            }
            $map = $this->removeMap($table, $_GPC);

            $modelname=substr($table,strlen(MODULE_NAME)+1);



            if(empty($map["id"])){
                $map["id"]=$this->create_guid();
                $user_id = $_W['uid'];
                if(!empty($user_id)){
                    $map["user_id"] =$user_id;
                }
                $map["create_time"] =  date("Y-m-d H:i:s", time());
                $map["update_time"] =  date("Y-m-d H:i:s", time());
                $map["status"] = "1";
                if(pdo_insert($table,$map)){
                    $info = ['id'=>$map["id"],'status'=>'success', 'message'=>'保存数据成功'];
                    echo json_encode($info);
                } else{
                    $info = ['status'=>'error', 'message'=>'保存数据失败'];
                    echo json_encode($info);
                }

            }else{
                $map["update_time"] = time();
                if(false !== pdo_update($table,$map,array('id'=>$map["id"]))){
                    $info = ['status'=>'success', 'message'=>'更新数据成功'];
                    echo json_encode($info);
                }else{
                    $info = ['status'=>'error', 'message'=>'更新数据失败'];
                    echo json_encode($info);
                }
            }
        } catch (Exception $e) {
            $info = ['status'=>'error', 'message'=>'更新数据失败'];
            echo json_encode($info);
            return;
        }
    }

    public function getTbName($table_name,$flag=true){
        $table_exist = pdo_tableexists($flag?getTableName($table_name):$table_name);
        if($table_exist){
            return getTableName($table_name);
        }else{
            return null;
        }
    }
    /**
     * 获取表名
     * @return string
     */
    public function getTable(){
        //实际环境中，大家要处理好这个表名的问题，要不然所有的数据都会被盗哟。本环境只是提供一个测试环境，所以简化了写法
        //大家可以做个表名影射，限制表的访问规则，哪些表不能访问，大家在实际环境可别这样用哟。
        global $_GPC;
        $dashboardid = safe_gpc_string($_GPC["dashboardid"]);
        if(empty($dashboardid)){
            $dashboardid = safe_gpc_string($_GPC["dashboardId"]);
        }
        $formid = safe_gpc_string($_GPC["formid"]);
        if(empty($formid)){
            $formid = safe_gpc_string($_GPC["formId"]);
        }

        $result = $this->getTbName($dashboardid."_".$formid);

        if($result){
            return $result;
        }
        $tableName = safe_gpc_string($_GPC["tableName"]);
        $result = $this->getTbName($dashboardid."_".$tableName);
        if($result){
            return $result;
        }

        $result = $this->getTbName($formid);
        if($result){
            return $result;
        }

        $map=[];
        $map["dashboard_id"] = $dashboardid;
        $map["form_id"] = $formid;

        $result = pdo_get(getTableName('MODEL'), $map , array('name'));

        if($result){
            $result = $this->getTbName($result["name"]);
            if($result){
                return $result;
            }
        }

        return null;

    }

    public function remove()
    {
        try {
            global $_GPC, $_W;
            $table = $this->getTable();//获取不带前缀的表名
            $ids    =   safe_gpc_array($_GPC['values']);
            $field    =   safe_gpc_string($_GPC['field']);
            $map[substr($field,0,strpos($field,"_"))] =$ids;
            if(pdo_delete($this->getTable(),$map)){
                $info = ['status'=>'success', 'message'=>'删除数据成功'];
                echo json_encode($info);
            }else{
                $info = ['status'=>'error', 'message'=>'删除数据失败'];
                echo json_encode($info);
            }

        } catch (\Exception $e) {
            $info = ['status'=>'error', 'message'=>'删除数据失败'];
            echo json_encode($info);
        }
    }
}
?>